<template>
    <ValidateFrom @from-submit="onSubmitForm">
        <label for="emailInput">Email address</label>
        <ValidateInput type="email" inputId="emailInput" :rules="emailRules" v-model="emailVal"></ValidateInput>
        <label for="passwordInput">Password</label>
        <ValidateInput type="password" inputId="passwordInput" :rules="passwordRules" v-model="password"></ValidateInput>
        <!-- <template #submit>
        <button type="submit" class="btn btn-danger me-3">submit</button>
        </template> -->
    </ValidateFrom>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateFrom from '../components/ValidateFrom.vue'
import createMessage from '../components/createMessage'

const emailVal = ref('')
const password = ref('')
const router = useRouter()
const store = useStore()

const emailRules: RulesProp = [
  { type: 'required', message: '电子邮件地址不能为空'},
  { type: 'email', message: '请输入正确的邮箱格式'}
]
const passwordRules: RulesProp = [
  { type: 'required', message: '密码不能为空'},
  { type: 'range', message: '密码不能少于6位，不能多于12位'}
]
const onSubmitForm = (result: boolean) => {
  if (result) {
    const payload = {
      email: emailVal.value,
      password: password.value
    }
    store.dispatch('loginAndFetch', payload).then(() => {
      createMessage('登录成功', 'success')
      router.push('/')
    }).catch((err: any) => {
      console.log(err)
    })
  }
}
</script>